package com.jee.ssm.common.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.common.config.Logger;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.model.Handheld;
import com.jee.ssm.model.WSSession;
import com.jee.ssm.modules.handheld.services.HandheldService;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class MessageWebSocketHandlerSocketPos extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message){
        Logger.socket(" 收到消息 === > "+ message.getPayload());
        String messages = message.getPayload();
        JSONObject jsonObject = JSON.parseObject(messages);
        String code = jsonObject.getString("number").trim();//编号
        String lng = jsonObject.getString("longitude").trim();//经度
        String lat = jsonObject.getString("latitude").trim();//纬度
        String battery = jsonObject.getString("battery").trim();//电量
        String userId = jsonObject.getString("userId").trim();//登录用户

        if (userId.equals("userId")){
            userId = "";
        }

        WSSession wsSession = new WSSession();
        wsSession.setCode(code);
        wsSession.setWebSocketSession(session);
        if (ZWSUtil.wssMap.get(code)==null){//第一次连接
            ZWSUtil.wssMap.put(code,wsSession);
        }
        //添加/更新手持机信息
        updateHandheld(code,lng,lat,battery,userId);
//        Map map = new HashMap();
//        map.put("type","我收到了！");

        try {
            ZWSUtil.wssMap.get(code).getWebSocketSession().sendMessage(new TextMessage("我收到了"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Logger.socket("收到：" + message.getPayload());
        /*TextMessage returnMessage = new TextMessage("服务器已收到！");
        session.sendMessage(returnMessage);*/
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        Logger.socket("一台手持机成功链接");
        super.afterConnectionEstablished(session);
    }

    //抛出异常时处理
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Logger.socket("会话关闭之后...");
        String code  = "";//用来存放被关闭链接的子终端的编号
        for (Map.Entry<String, WSSession> entry : ZWSUtil.wssMap.entrySet()){
            if (entry.getValue().getWebSocketSession().equals(session)){//这个链接关闭了
                code = entry.getKey();
                ZWSUtil.wssMap.remove(code);
                Handheld handheld = handheldService.selectByNumber(code);
                handheld.setPosStatus(0);
                handheld.setLastTime(new Date());
                handheld.setUserId("");
                handheldService.updateById(handheld);
            }
        }
        super.afterConnectionClosed(session, status);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 添加/更新手持机信息
     * @param code 编号
     * @param lng 经度
     * @param lat 维度
     * @param battery 电量
     */
    public void updateHandheld(String code,String lng,String lat,String battery,String userId){
        Handheld handheld = handheldService.selectByNumber(code);
        try {
            if (handheld != null){
                Handheld h = new Handheld(handheld.getId(),1,lng,lat,battery,new Date(),userId);
                handheldService.updateById(h);
            }else{
                Handheld h = new Handheld(UUIDFactory.getStringId(),code,1,lng,lat,battery,0,new Date(),new Date(),userId);
                handheldService.insert(h);
            }
        }catch (Exception e){
            //e.printStackTrace();
        }
    }

    @Resource
    private HandheldService handheldService;

}
